package com.wgts.wgts.mvp.view.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseFragment;
import com.wgts.wgts.control.nestedscrollview.ColorFlipPagerTitleView;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerHomePageFragmentComponent;
import com.wgts.wgts.dagger.module.HomePageFragmentModule;
import com.wgts.wgts.mvp.presenter.IHomePageFragmentPersenter;
import com.wgts.wgts.mvp.view.IHomePageFragmentView;
import com.wgts.wgts.mvp.view.activity.login.LoginActivity;
import com.wgts.wgts.mvp.view.activity.main.MoHuMainActivity;
import com.wgts.wgts.mvp.view.activity.message.MessageActivity;
import com.wgts.wgts.mvp.view.activity.otherhomepage.OtherFragment;
import com.wgts.wgts.mvp.view.activity.search.SearchActivity;
import com.wgts.wgts.mvp.view.callback.IHomePageActivityCallbackFragment;
import com.wgts.wgts.netmodle.resp.ProductClassEntity;
import com.wgts.wgts.netmodle.resp.VipMessageEntity;
import com.wgts.wgts.tools.AppInfor;
import com.wgts.wgts.tools.MoHuGlide;
import com.wgts.wgts.tools.VipMessageDate;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class HomePageFragment extends BaseFragment implements IHomePageActivityCallbackFragment, IHomePageFragmentView {


    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.view_page_home)
    ViewPager viewPageHome;
    Unbinder unbinder;
    @BindView(R.id.relative_layout)
    RelativeLayout relativeLayout;
    //@BindView(R.id.time_table_layout)
    //TabLayout timeTableLayout;
    @BindView(R.id.linear_magic)
    LinearLayout linearMagic;
    @BindView(R.id.img_search)
    ImageView imgSearch;
    @BindView(R.id.img_msg)
    ImageView imgMsg;
    @BindView(R.id.linear_title)
    LinearLayout linearTitle;
    @BindView(R.id.img_net_work_error)
    ImageView imgNetWorkError;
    @BindView(R.id.linear_net_error)
    LinearLayout linearNetError;

    private ArrayList<Fragment> fragments;
    private Animation hiddenAnima, showAnim;

    private boolean isShow;

    private HomePageFragmentToMohuMainActivity homePageFragmentToMohuMainActivity;

    private List<ProductClassEntity> productClassEntityList;


    @Override
    public void onAttach(Context context){
        super.onAttach(context);
        homePageFragmentToMohuMainActivity = (HomePageFragmentToMohuMainActivity)context;
    }

    @Inject
    IHomePageFragmentPersenter persenter;

    @Override
    public void init() {
        DaggerHomePageFragmentComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .homePageFragmentModule(new HomePageFragmentModule(this))
                .build()
                .inject(this);

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.home_page_fragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void initView() {

        persenter.initProductClass();

    }


    private void initMagicIndicator(final List<ProductClassEntity> productClassEntities) {


        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setScrollPivotX(0.65f);
        commonNavigator.setAdjustMode(false);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return productClassEntityList == null ? 0 : productClassEntityList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setText(productClassEntityList.get(index).typeName);
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(getActivity(), R.color.nomal));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(getActivity(), R.color.home_page_color));
                simplePagerTitleView.setTextSize(14);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPageHome.setCurrentItem(index, false);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 2));
                indicator.setLineWidth(UIUtil.dip2px(context, 30));
                indicator.setRoundRadius(UIUtil.dip2px(context, 1));
                indicator.setYOffset(UIUtil.dip2px(context, 5));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(ContextCompat.getColor(getContext(), R.color.home_page_color));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, viewPageHome);
    }


    private void initViewPage(List<ProductClassEntity> productClassEntities) {

        fragments = new ArrayList<>();


        for (int i = 0; i < productClassEntities.size(); i++) {
            if (i == 0) {
                fragments.add(new HomePageContentFragment());
            } else {
                fragments.add(OtherFragment.getInstanceBundle(String.valueOf(productClassEntities.get(i).typeId)));
            }
        }

        FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragments.get(i);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        };
        viewPageHome.setAdapter(fragmentPagerAdapter);

        viewPageHome.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if(i != 0 && !isShow){
                    showMagicIndicator();
                }

                if(i == 0 && !isShow){
                    hideMagicIndicator();
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }


    @Override
    public void hideMagicIndicator() {
        hiddenAnima = AnimationUtils.loadAnimation(getContext(), R.anim.navigation_hidden_anim);
        linearMagic.startAnimation(hiddenAnima);
        linearMagic.setVisibility(View.GONE);
        magicIndicator.setVisibility(View.GONE);
        isShow = false;
    }

    @Override
    public void showMagicIndicator() {
        showAnim = AnimationUtils.loadAnimation(getContext(), R.anim.navigation_show_anim);
        linearMagic.startAnimation(showAnim);
        linearMagic.setVisibility(View.VISIBLE);
        magicIndicator.setVisibility(View.VISIBLE);
        isShow = true;
    }

    @Override
    public void initProductClassResult(List<ProductClassEntity> productClassEntities) {
        linearNetError.setVisibility(View.GONE);
        productClassEntityList = productClassEntities;
        if (productClassEntities != null && productClassEntities.size() != 0) {
            initViewPage(productClassEntities);
            initMagicIndicator(productClassEntities);
        }
    }

    @Override
    public void vipMessage(List<VipMessageEntity> vipMessageEntitys) {
        VipMessageDate.getInstance().setList(vipMessageEntitys);
    }

    @Override
    public void onError(int status, String msg) {
        linearNetError.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.img_search, R.id.img_msg,R.id.linear_net_error})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_search:
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.img_msg:
                if (AppInfor.getInstance().getRefreshToken() != null && !AppInfor.getInstance().getRefreshToken().equals("")) {
                    Intent intent1 = new Intent(getActivity(), MessageActivity.class);
                    startActivity(intent1);
                } else {
                    Intent intent2 = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent2);
                }
                break;
            case R.id.linear_net_error:
                refresh();
                break;
        }
    }

    private void refresh(){
        persenter.initProductClass();
        persenter.userInfo();
        if(homePageFragmentToMohuMainActivity != null){
            homePageFragmentToMohuMainActivity.refresh();
        }
    }





    public interface HomePageFragmentToMohuMainActivity{
        void refresh();
    }

    public void updateSuccess(){
        if (persenter != null){
            persenter.initProductClass();
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @SuppressWarnings("deprecation")
        @Override
        public void onReceive(Context context, Intent intent) {

            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            Bundle bundle = intent.getExtras();
            NetworkInfo aNetworkInfo = (NetworkInfo) bundle.get(ConnectivityManager.EXTRA_NETWORK_INFO);

            if (aNetworkInfo != null) {
                if (!wifi.isConnected() && !mobile.isConnected()) {
                    linearNetError.setVisibility(View.VISIBLE);
                    //表示网络已连接
                }
            }
        }
    };

    @Override
    public void onResume(){
        super.onResume();
        //getContext().registerReceiver(mBroadcastReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    public void onPause(){
        super.onPause();
        //getContext().unregisterReceiver(mBroadcastReceiver);;
    }

    public void checkList(){
        if(productClassEntityList == null || productClassEntityList.size() == 0){
            if(persenter != null){
                persenter.initProductClass();
            }
        }
    }
}
